﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AVIS.OutBound.Stores.Cache;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AVIS.OutBound.Stores
{
    /// <summary>
    /// 门店的领域服务
    /// </summary>
    public class StoreManager : DomainService, IStoreManager
    {
        #region 构造函数
        private readonly ICacheManager _cacheManager;
        private readonly IObjectMapper _objectMapper;
        private readonly IStoreRepository _storeRepository;
        public StoreManager(
            ICacheManager cacheManager,
            IObjectMapper objectMapper,
            IStoreRepository storeRepository)
        {
            _objectMapper = objectMapper;
            _cacheManager = cacheManager;
            _storeRepository = storeRepository;
        }
        #endregion

        /// <summary>
        /// 获取指定Code门店信息
        /// </summary>
        /// <returns></returns>
        public Store GetStoreByCode(string storeCode)
        {
            var cacheKey = storeCode.ToUpper();
            var cacheItems = _cacheManager.GetStoreCache().Get(cacheKey, f =>
            {
                var data = _storeRepository.GetStoreByCode(storeCode);
                return _objectMapper.Map<List<StoreCacheItem>>(new List<Store> { data });
            });
            return _objectMapper.Map<Store>(cacheItems.FirstOrDefault());
        }

        /// <summary>
        /// 获取指定城市的门店（包含附近门店）
        /// </summary>
        public List<Store> GetStoresByCity(string cityCode, string regionCode)
        {
            // 查询指定城市里所有门店的附近门店AGDCode（AGDCode != "999"）
            var cacheKey = cityCode.ToUpper() + "_" + regionCode.ToUpper();
            var list = _cacheManager.GetStoreCache().Get(cacheKey, f =>
            {
                var storeList = _storeRepository.GetStoresByCity(cityCode, regionCode);
                return _objectMapper.Map<List<StoreCacheItem>>(storeList);
            });

            return _objectMapper.Map<List<Store>>(list);
        }
    }
}
